package cn.mrlong.recordandplay;

import android.media.AudioManager;
import android.media.MediaPlayer;

public class PlayRecordUtil {

    private static MediaPlayer mPlayer;
    //释放暂停播放
    private static boolean isPause = false;

    public static void playSound(String filePath) {
        if (mPlayer == null) {
            mPlayer = new MediaPlayer();
        } else {
            mPlayer.reset();
        }
        mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        //播放完毕的监听
        mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                // 播放完毕改变状态，释放资源
                release();
            }
        });
        mPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                mPlayer.reset();
                return false;
            }
        });
        try {
            // 播放所选中的录音
            mPlayer.setDataSource(filePath);
            mPlayer.prepare();
            mPlayer.start();
        } catch (Exception e) {
            // 若出现异常被捕获后，同样要释放掉资源
            // 否则程序会不稳定，不适合正式项目上使用
            e.printStackTrace();
            release();
        }

        isPause = false;
    }

    /**
     * 暂停播放
     */
    public static void pause() {
        if (mPlayer != null && mPlayer.isPlaying()) {
            mPlayer.pause();
            isPause = true;
        }
    }

    /**
     * 继续
     */
    public static void resume() {
        if (mPlayer != null && isPause) {
            mPlayer.start();
            isPause = false;
        }
    }

    /**
     * 释放资源 停止
     */
    public static void release() {
        if (mPlayer != null) {
            if (mPlayer.isPlaying()){
                mPlayer.stop();
            }
            mPlayer.release();
            mPlayer = null;
        }
        isPause = false;
    }
}
